<template>
  <div class="product-list-container">
    <h2 class="category-title">{{ categoryName }}</h2>

    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      加载中...
    </div>

    <div v-else-if="error" class="error-message">
      <div class="error-icon">⚠️</div>
      <div class="error-text">{{ error }}</div>
      <button class="retry-btn" @click="fetchProducts">重试</button>
    </div>

    <div v-else-if="products.length === 0" class="empty-message">
      暂无商品数据
    </div>

    <div v-else class="product-grid">
      <div
          v-for="product in products"
          :key="product.productId"
          class="product-card"
          @click="goToProductDetail(product.productId)"
      >
        <div class="product-image">
          <img :src="getProductImage(product)" :alt="product.productName" />
          <span v-if="product.isHot === 1" class="hot-tag">热销</span>
        </div>

        <div class="product-info">
          <h3 class="product-name">{{ product.productName }}</h3>
          <div class="price-section">
            <span class="current-price">¥{{ formatPrice(product.sellingPrice) }}</span>
            <span v-if="product.originalPrice" class="original-price">¥{{ formatPrice(product.originalPrice) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import request from '../../utils/request';

// 定义props
const props = defineProps({
  selectedCategoryId: {
    type: [String, Number],
    default: '',
    validator: value => value === '' || !isNaN(Number(value))
  }
});

// 响应式数据
const products = ref([]);
const loading = ref(false);
const error = ref(null);
const categoryMap = ref({
  1: '建筑起重机械',
  2: '工程起重器械',
  3: '路面机械',
  4: '土方机械',
  5: '环卫机械',
  6: '工业车辆',
  7: '模型专区',
  8: '特惠专区',
  9: '运费'
});

// 获取store和router
const store = useStore();
const router = useRouter();

// 计算属性
const currentUser = computed(() => store.state.currentUser);
const categoryName = computed(() => {
  if (!props.selectedCategoryId) return '所有商品';
  return categoryMap.value[props.selectedCategoryId] || `分类ID: ${props.selectedCategoryId}`;
});

// 方法
const formatPrice = (price) => {
  // 处理价格显示，确保是数字类型
  const num = Number(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

const goToProductDetail = (productId) => {
  // 确保 productId 是数字类型
  const id = Number(productId);
  console.log('Attempting to navigate to product detail:', { productId, id });
  
  if (isNaN(id)) {
    console.error('Invalid product ID:', productId);
    return;
  }
  
  // 使用路径导航而不是名称
  router.push(`/product/${id}`).catch(err => {
    console.error('Navigation failed:', err);
  });
};

const getProductImage = (product) => {
  return product.productImg || require('@/assets/product-default.png');
};

const fetchProducts = async () => {
  try {
    loading.value = true;
    error.value = null;

    // 调试日志
    console.log('Fetching products for category:', props.selectedCategoryId);

    const url = props.selectedCategoryId
        ? `/products/category/${Number(props.selectedCategoryId)}`
        : '/products';

    const response = await request.get(url);
    products.value = response.data;

    // 调试日志
    console.log('Received products:', products.value);
  } catch (error) {
    console.error('获取商品列表失败:', error);
    error.value = error.response?.data?.message || '获取商品列表失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 监听器
watch(() => props.selectedCategoryId, (newVal, oldVal) => {
  // 只有分类ID真正变化时才重新获取数据
  if (newVal !== oldVal) {
    fetchProducts();
  }
}, { immediate: true });
</script>

<style scoped>
.product-list-container {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.category-title {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.loading {
  padding: 2rem;
  text-align: center;
  color: #666;
  font-size: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #f5222d;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  padding: 2rem;
  text-align: center;
  background-color: #fff1f0;
  border-radius: 8px;
  margin: 1rem 0;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.error-text {
  color: #f5222d;
  margin-bottom: 1rem;
}

.retry-btn {
  padding: 0.5rem 1.5rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.hot-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #f5222d;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.product-info {
  padding: 15px;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px;
  height: 44px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-section {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.current-price {
  font-size: 18px;
  color: #f5222d;
  font-weight: bold;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .product-image {
    height: 150px;
  }
}

@media (max-width: 480px) {
  .product-grid {
    grid-template-columns: 1fr;
  }
}
</style>